package com.project.service.bloom;


import lombok.extern.slf4j.Slf4j;
import org.redisson.Redisson;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.stereotype.Service;


@Slf4j
@Service
public class BloomFilterService {

    private static final int BLOOM_FILTER_SIZE = 1000000;
    private static final double ERROR_RATE = 0.01;

    private final RedissonClient redissonClient;

    public BloomFilterService() {
        Config config = new Config();
        config.useSingleServer()
                .setAddress("redis://10.3.2.80:6379")
                .setPassword("Ol2q1qBV");
        this.redissonClient = Redisson.create(config);
    }

    public void initBloomFilter(String bloomFilterName) {
        log.info("初始化布隆过滤器......");
        RBloomFilter<Object> bloomFilter = redissonClient.getBloomFilter(bloomFilterName);
        if (!bloomFilter.isExists()) {
            if (!bloomFilter.tryInit(BLOOM_FILTER_SIZE, ERROR_RATE)) {
                throw new IllegalStateException("Failed to initialize bloom filter: " + bloomFilterName);
            }
        } else {
            log.info("Bloom filter already exists: " + bloomFilterName);
        }
    }

    public void addToBloomFilter(String bloomFilterName, Object value) {
        RBloomFilter<Object> bloomFilter = redissonClient.getBloomFilter(bloomFilterName);
        bloomFilter.add(value);
    }

    public boolean mightContain(String bloomFilterName, Object value) {
        RBloomFilter<Object> bloomFilter = redissonClient.getBloomFilter(bloomFilterName);
        return bloomFilter.contains(value);
    }

}
